<script>
	import BookCard from './BookCard.svelte';
	let books = [];
	let booksInCart = [];
	let title = '';
	let price = 0;
	let descriptions = '';
	$: bookAmount = booksInCart.reduce((p, c) => p + c.count, 0);
	$: subtotal = booksInCart.reduce((p, c) => p + c.price * c.count, 0);

	function addBookHandle() {
		if (books.some(book => book.title === title)) return alert('已存在的书名！');
		books = books.concat({
			title,
			price,
			descriptions
		});
		title = '';
		price = 0;
		descriptions = '';
	}

	function addToCartHandle(title) {
		const book = Object.assign({ count: 1 }, books.find(item => item.title === title));
		const bookInCart = booksInCart.find(item => item.title === title);
		if (bookInCart) {
			bookInCart.count++;
			booksInCart = booksInCart.slice();
		} else {
			booksInCart = booksInCart.concat(book);
		}
	}
</script>

<main>
	<section class="form">
		<h1>Add New Book</h1>
		<label for="title">Title</label>
		<input type="text" id="title" bind:value={title} >
		<label for="price">Price</label>
		<input type="text" id="price" bind:value={price}>
		<label for="descriptions">Descriptions</label>
		<textarea rows="3" id="descriptions" bind:value={descriptions}></textarea>
		<div>
			<button on:click={addBookHandle}>Add Book</button>
		</div>
	</section>
	<section>
		<h3>Cart</h3>
		{#if booksInCart.length === 0}
			<div>购物车空空如也~</div>
		{:else}
			<div>Amount: {bookAmount}</div>
			<div>Subtotal: {subtotal}</div>
			{#each booksInCart as { title, price, count }}
			<div>Title: {title}, Price: {price}, count: {count}, sum: {price * count}</div>
		{/each}
		{/if}
	</section>
	<section>
		<h3>Shelf</h3>
		{#each books as { title, price, descriptions }}
			<BookCard {title} {price} {descriptions} {addToCartHandle}/>
		{/each}
	</section>
</main>

<style>
	main {
		text-align: center;
		padding: 1em;
		max-width: 240px;
		margin: 0 auto;
	}

	h1 {
		color: #ff3e00;
		text-transform: uppercase;
		font-size: 4em;
		font-weight: 100;
	}

	button {
    background-color: #ff3e00;
    color: white;
    border-radius: 5px;
    cursor: pointer;
    border: none;
  }

	@media (min-width: 640px) {
		main {
			max-width: none;
		}
	}
</style>